# algorithm/models/tag_importance.py
from django.db import models
from django.contrib.auth.models import User
from ..utils import mastery_level1, diff_max_score
from users.models import User as CustomUser  # 自定义的User表
from tag.models import AlgorithmTag
from problems.models import Problem
import logging
logger = logging.getLogger('algorithm')


# 标签价值模型
class TagImportance(models.Model):
    tag = models.ForeignKey(AlgorithmTag, on_delete=models.CASCADE, to_field='index', db_column='tag_index',primary_key=True)
    importance_score = models.FloatField(default=0.0)

    def __str__(self):
        return f"Tag {self.tag.index} Importance: {self.importance_score}"

    # 使用类中静态方法创建
    @classmethod
    def create_or_update_tag_importance(cls, tag_index):
        try:
            # 先计算标签的重要性分数
            importance_score = cls.calculate_tag_importance(tag_index)
            # 获取对应的 AlgorithmTag 对象
            tag = AlgorithmTag.objects.get(index=tag_index)
            # 创建或更新 TagImportance 对象
            tag_importance_obj, created = cls.objects.update_or_create(
                tag=tag,
                defaults={'importance_score': importance_score}
            )
            # 返回创建或更新的对象和创建标记
            logger.info(f"{cls.__name__}.create_or_update_tag_importance : successfully created tag importance {tag_index}")
            return tag_importance_obj, created
        except AlgorithmTag.DoesNotExist:
            logger.error(
                f"{cls.__name__}.create_or_update_tag_importance : Tag with index {tag_index} does not exist")
            print(f"Tag with index {tag_index} does not exist.")
            return None, False

    @classmethod
    def calculate_tag_importance(cls, tag_index):
        try:
            # 获取指定索引的 AlgorithmTag 对象
            tag = AlgorithmTag.objects.get(index=tag_index)
            problems = tag.problems.all()  # 获取关联的所有问题
        except AlgorithmTag.DoesNotExist:
            print(f"Tag with index {tag_index} does not exist.")
            logger.error(f"{cls.__name__}.calculate_tag_importance : Tag with index {tag_index} does not exist")
            return None

        # 初始化难度计数数组，假设难度从0到7
        difficulty_counts = [0] * 8

        # 计算各难度下的题目数量
        for problem in problems:
            if 0 <= problem.difficulty_index < len(difficulty_counts):
                difficulty_counts[problem.difficulty_index] += 1

        # 难度分数上限
        total_score = 0.0
        total_questions = sum(difficulty_counts)  # 总题数
        num_difficulties = len(difficulty_counts) - 1  # 参与计算的难度数量

        if total_questions > 0:
            for i, count in enumerate(difficulty_counts):
                if i == 0:  # 跳过0难度
                    continue
                initial_ratio = min(1.0, count / (total_questions / num_difficulties))
                adjusted_ratio = mastery_level1(initial_ratio)  # 需要定义mastery_level映射函数
                score = adjusted_ratio * diff_max_score[i]
                total_score += score

        # 应用题目数量的罚分逻辑
        if total_questions < 20:
            total_score *= 0.7
        elif 20 <= total_questions < 40:
            total_score *= 0.8
        elif 40 <= total_questions < 80:
            total_score *= 0.85
        elif 80 <= total_questions < 150:
            total_score *= 0.9
        logger.info(f"{cls.__name__}.calculate_tag_importance : successfully calculated tag importance tag_index{tag_index}")
        return total_score

    @classmethod
    def create_all_tag_importance(cls):
        # 获取所有的算法标签
        all_tags = AlgorithmTag.objects.all()  # 使用 AlgorithmTag 代替 Tag

        for tag in all_tags:
            # 调用 TagImportance 类的方法，创建或更新每个标签的 TagImportance
            tag_importance_obj, created = TagImportance.create_or_update_tag_importance(tag.index)

            # 检查返回的对象是否有效，并打印相应的结果
            if tag_importance_obj is not None:

                print(f'Successfully {"created" if created else "updated"} TagImportance for tag {tag.index}')
            else:
                print(f"Failed to create or update TagImportance for tag {tag.index}")
        logger.info(f"{cls.__name__}.create_all_tag_importance : successfully created all TagImportance")

    @classmethod
    def clear_all_tag_importance(cls):
        # 删除 TagImportance 模型中的所有记录
        cls.objects.all().delete()
        print("All TagImportance records have been cleared.")
        logger.info(f"{cls.__name__}.clear_all_tag_importance : successfully cleared all TagImportance")